package cn.sdc.bugKiller.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import cn.sdc.sfw.util.ReflectUtil;
import cn.sdc.sfw.util.StringUtil;
import cn.sdc.sfw.util.TypeUtil;

public class ParamUtil {
	
	public static void copyBean(HttpServletRequest fromReq, Object toBean) {
		copyBean(fromReq, StringUtil.EMPTY_STRING, toBean);
	}
	
	public static void copyBean(HttpServletRequest fromReq, String beanName, Object toBean) {
		copyBean(fromReq, beanName, toBean, new String[]{""});
	}

	public static void copyBean(HttpServletRequest fromReq, Object toBean,
			String[] filteredFieldNames) {
		copyBean(fromReq, StringUtil.EMPTY_STRING, toBean, filteredFieldNames);
	}
	
	public static void copyBean(HttpServletRequest fromReq, String beanName, Object toBean,
			String[] filteredFieldNames) {
		String[] temp = new String[filteredFieldNames.length + 1];
		System.arraycopy(filteredFieldNames, 0, temp, 0, filteredFieldNames.length);
		copyExpectedFiledBean(fromReq, beanName, toBean, temp, false);
	}
	
	public static void copyExpectedFiledBean(HttpServletRequest fromReq, Object toBean,
			String[] expectedFieldNames) {
		copyExpectedFiledBean(fromReq, StringUtil.EMPTY_STRING, toBean, expectedFieldNames);
	}
	
	public static void copyExpectedFiledBean(HttpServletRequest fromReq, String beanName, Object toBean,
			String[] expectedFieldNames) {
		copyExpectedFiledBean(fromReq, beanName, toBean, expectedFieldNames, true);
	}
	
	private static void copyExpectedFiledBean(HttpServletRequest fromReq, String beanName, Object toBean,
			String[] FieldNames, boolean isExpected){
		
		if (fromReq == null || toBean == null) {
			return;
		}
		Field[] toFields = toBean.getClass().getDeclaredFields();
		Object value;
		String fieldName;
		Class fieldClass;
		String beanPrefix = StringUtil.EMPTY_STRING;
		if(beanName!=null && !beanName.isEmpty()){
			beanPrefix = beanName + ".";
		}
		List<String> fieldNamesArr = new ArrayList<String>();
		if (FieldNames != null && FieldNames.length > 0) {
			fieldNamesArr = Arrays.asList(FieldNames);
		}
		for (int i = 0; i < toFields.length; i++) {
			fieldName = toFields[i].getName();
			fieldClass = toFields[i].getType();
			if( (isExpected && fieldNamesArr.contains(fieldName))
					|| (! isExpected && !fieldNamesArr.contains(fieldName)) ){
					value = TypeUtil.toObject(fromReq.getParameter(beanPrefix+fieldName), fieldClass);
					ReflectUtil.setFieldValue(toBean, fieldName, value);
			}
		}
	}
}
